package cn.ccbfund.common.util;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

/**
 * 用户相关工具类
 */
public class UserUtils {
    private static final ThreadLocal<String> THREAD_LOCAL_USER = new ThreadLocal<String>();
    private static final String KEY_USER = "user";

    /**
     * 根据请求heard中的token获取用户角色
     *
     * @param httpServletRequest request
     * @return 角色名
     */
    @SuppressWarnings("unchecked")
	public static List<String> getRole(HttpServletRequest httpServletRequest) {
        String token = getToken(httpServletRequest);
        String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        List<String> roleCodes = (List<String>) claims.get("authorities");
        return roleCodes;
    }

    /**
     * 从HttpRequest中获得当前登录人的授权范围
     * @param httpServletRequest
     * @return
     */
    public static Long getScope(HttpServletRequest httpServletRequest) {
    	Long scope = null; //默认建信基金
    	HashMap<String, Object> map = getUserVO(httpServletRequest);
    	Object obj = map.get("scope");
    	if(obj != null) {
    		scope = Long.parseLong(obj.toString());
    	}
    	return scope;
    }
    
    /**
     * 从HttpRequest中获得当前登录人信息
     * @param httpServletRequest
     * @return
     */
    @SuppressWarnings("unchecked")
	public static HashMap<String, Object> getUserVO(HttpServletRequest httpServletRequest){
        String token = getToken(httpServletRequest);
        if(token == null) {
        	return null;
        }
        String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        HashMap<String, Object> map = (HashMap<String, Object>)claims.get("user");
        return map;
    }
    
    /**
     * 获取请求中token
     *
     * @param httpServletRequest request
     * @return token
     */
    public static String getToken(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader(CommonConstant.REQ_HEADER);
        return StringUtils.substringAfter(authorization, CommonConstant.TOKEN_SPLIT);
    }

    /**
     * 设置用户信息
     *
     * @param username 用户名
     */
    public static void setUser(String username) {
        THREAD_LOCAL_USER.set(username);
        MDC.put(KEY_USER, username);
    }

    /**
     * 从threadlocal 获取用户名
     *
     * @return 用户名
     */

    public static String getUser() {
        return THREAD_LOCAL_USER.get();
    }

    public static void clearAllUserInfo() {
        THREAD_LOCAL_USER.remove();
        MDC.remove(KEY_USER);
    }
}
